package com.itheima.edu.info.manager.controller;

import com.itheima.edu.info.manager.domain.Fruit;
import com.itheima.edu.info.manager.domain.User;
import com.itheima.edu.info.manager.service.FruitService;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public abstract class BaseManagerController {
    private FruitService fruitService = new FruitService();
    private static ArrayList<User> users = new ArrayList<>();
    private Scanner sc = new Scanner(System.in);
    {
        users.add(new User("heima001", "123456"));
        users.add(new User("heima002", "123456"));
        users.add(new User("heima003", "123456"));
        BufferedWriter bw = null;
        try {
            bw = new BufferedWriter(new FileWriter("FruitMarket\\user.txt"));
            for (int i = 0; i < users.size(); i++) {
                bw.write(users.get(i).getName() + "," + users.get(i).getPassword());
                bw.newLine();
                bw.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bw != null) {
                try {
                    bw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void start() {
        Loop:
        lo:
        while (true) {
            System.out.println("请输入您的用户名:");
            String name = sc.next();
            System.out.println("请输入您的密码:");
            String passWord = sc.next();
            Lo:
            while (true) { // 不清楚输入多少次，定义死循环，输入正确时跳出即可。
                String code = getRandomCode();
                System.out.println("请输入验证码 " + code);
                String s = sc.next();
                // 不区分大小写比较是否相等
                if (code.equalsIgnoreCase(s)) {
                    System.out.println("验证码输入正确");
                    break; // 跳出循环，结束程序
                } else {
                    System.out.println("验证码输入错误，请重新输入!");
                    continue Lo;
                }
            }

            boolean result = false;
            for (int i = 0; i < users.size(); i++) {
                if (name.equals(users.get(i).getName()) && passWord.equals(users.get(i).getPassword())) {
                    result = true;
                    break;
                }
            }
            if (result) {
                System.out.println("您好!尊敬的" + name + "管理员!");
            } else {
                System.out.println("用户名和密码输入错误!请重新输入用户名和密码!");
                continue lo;
            }

            while (true) {
                System.out.println("请输入您的选择: 1.查看水果  2.添加水果  3.修改水果  4.删除水果  5.退出");
                String choice = sc.next();
                switch (choice) {
                    case "1":
                        findAllFruit();
                        break;
                    case "2":
                        addFruit();
                        break;
                    case "3":
                        updateFruit();
                        break;
                    case "4":
                        deleteFruit();
                        break;
                    case "5":
                        System.out.println("感谢您的使用!");
                        break Loop;
                    default:
                        System.out.println("您的输入有误, 请重新输入");
                        break;
                }
            }
        }
    }

    //删除
    private void deleteFruit() {
        String delId = inputFruitId();
        // 调用业务员中的deleteFruitById根据id, 删除水果
        fruitService.deleteFruit(delId);
        // 提示删除成功
        System.out.println("删除成功!");
    }

    //修改
    private void updateFruit() {
        String updateId = inputFruitId();
        Fruit newFruit = inputFruitInfo(updateId);
        fruitService.updateFruit(updateId, newFruit);

        System.out.println("修改成功!");
    }

    // 添加学生方法
    public final void addFruit() {
        String id;
        while (true) {
            System.out.println("请输入水果编号:");
            id = sc.next();
            boolean flag = fruitService.isExists(id);
            if (flag) {
                System.out.println("该编号已有, 请重新输入");
            } else {
                break;
            }
        }

        Fruit fruit = inputFruitInfo(id);

        // 将水果对象传递给FruitService(业务员)中的addFruit方法
        boolean result = fruitService.addFruit(fruit);
        // 根据返回的boolean类型结果, 在控制台打印成功\失败
        if (result) {
            System.out.println("添加成功!");
        } else {
            System.out.println("添加失败!");
        }
    }

    // 键盘录入水果id
    public String inputFruitId() {
        String id;
        while (true) {
            System.out.println("请输入水果编号:");
            id = sc.next();
            boolean exists = fruitService.isExists(id);
            if (!exists) {
                System.out.println("您输入的编号不存在, 请重新输入:");
            } else {
                break;
            }
        }
        return id;
    }

    // 键盘录入水果信息
    // 开闭原则: 对扩展内容开放, 对修改内容关闭
    public abstract Fruit inputFruitInfo(String id);

    private void findAllFruit() {
        // 1. 调用业务员中的获取方法, 得到水果的对象数组
        Fruit[] fruits = fruitService.findAllFruit();
        // 2. 判断数组的内存地址, 是否为null
        if (fruits == null) {
            System.out.println("查无信息, 请添加后重试");
            return;
        }
        // 3. 遍历数组, 获取水果信息并打印在控制台
        System.out.println("编号\t名称\t价格(元/斤)\t\t库存(斤)");
        for (int i = 0; i < fruits.length; i++) {
            Fruit f = fruits[i];
            if (f != null) {
                System.out.println(f.getId() + "\t\t" + f.getFruitName() + "\t" + f.getFruitPrice() + "\t\t\t\t" + f.getInventory());
            }
        }
    }

    // 验证码功能
    public  String getRandomCode () {
        // 准备数据
        StringBuilder sb = new StringBuilder();
        for (char ch = 'a'; ch <= 'z'; ch++) {
            sb.append(ch);
        }
        for (char ch = 'A'; ch <= 'Z'; ch++) {
            sb.append(ch);
        }
        for (char ch = '0'; ch <= '9'; ch++) {
            sb.append(ch);
        }
        // 随机获取四位
        Random r = new Random();
        String code = "";
        for (int i = 0; i < 4; i++) {
            // 字符串中的字符有索引，随机获取一个索引即相当于随机获取到了该索引的字符
            int index = r.nextInt(sb.length()); // 从索引0（包含）到字符串的长度（不包含）
            code += sb.charAt(index); // 获取该索引上的字符
        }
        // 返回结果
        return code;
    }
}
